<template>
	<!-- 不能用v-if (i: 每个tab页的专属下标;  index: 当前tab的下标; 申明在 MescrollMoreItemMixin )-->
	<view v-show="i === index">
		<!-- top="88"下拉布局往下偏移,防止被悬浮菜单遮住 -->
		<mescroll-body ref="mescrollRef" top="88" @init="mescrollInit" @down="downCallback" @up="upCallback" :down="downOption"
		 :up="upOption">

			<!-- 外层主订单列表 -->
			<view v-for="(item,index) in dataList" :key="index" class="order-item">

				<!--未付款或者取消订单，需要显示主订单-->
				<view v-if="item.is_paid === 0 " @click="orderDetails(item.id, item.is_paid, index)">
					<view class="i-top">
						<text class="order_number">总订单号：{{item.id}}</text>
						<text class="state" style="color: #E52631">{{item.status | orderStateExp}}</text>
						<!-- <text v-if="item.status===2" class="del-btn yticon icon-iconfontshanchu1" @click="operationOrder(item, 1, 'delete')"></text> -->
					</view>

					<!--一个子订单的情况-->
					<view v-if="item.order_items.length === 1" class="goods-box-single" v-for="(goodsItem, goodsIndex) in item.order_items"
					 :key="goodsIndex">
						<image class="goods-img" :src="imgsrc + goodsItem.product_pic" mode="aspectFill"></image>
						<view class="right">
							<text class="title clamp">{{goodsItem.product_name}}</text>
							<!-- {{goodsItem.product_attr}} -->
							<text class="attr-box">x {{goodsItem.product_quantity}}</text>
							<text class="price">{{goodsItem.product_price}}</text>
						</view>
					</view>

					<!--多个子订单的情况-->
					<scroll-view v-if="item.order_items.length > 1" class="goods-box" scroll-x>
						<view v-for="(goodsItem, goodsIndex) in item.order_items" :key="goodsIndex" class="goods-item">
							<image class="goods-img" :src="imgsrc + goodsItem.product_pic" mode="aspectFill"></image>
						</view>
					</scroll-view>

					<view v-if="item.status == 0" class="price-box">
						<text>共</text>
						<text class="num">{{item.order_items.length}}</text>
						<text>件商品 需付款</text>
						<text class="price">{{item.pay_amount}}</text>
					</view>

					<view class="action-box">
						<template v-if="item.status == 0">
							<!-- <button class="action-btn" @click.stop="operationOrder(1, 'cancel', index)">取消订单</button> -->
							<button class="action-btn recom" @click.stop="pay(item.id)">立即支付</button>
						</template>
						<template v-else-if="item.status == 2">
							<button class="action-btn" @click.stop="operationOrder(1, 'delete', index)">删除订单</button>
						</template>
					</view>
					<!-- <view class="action-box" v-if="item.status == 2">
							<button class="action-btn" @click="cancelOrder(item)">已经关闭</button>
						</view> -->
				</view>

				<!--完成付款 需要显示多个子订单的情况-->
				<view v-if="item.is_paid === 1" v-for="(order, index) in item.orders" :key="index" @click="orderDetails(order.id,item.is_paid, index)">
					<view class="i-top">
						<text class="order_number">订单号：{{order.id}}</text>
						<text class="state" style="color: #E52631">{{order.status | orderStateExp}}</text>
						<!-- <text v-if="order.state===12" class="del-btn yticon icon-iconfontshanchu1" @click.stop="deleteOrder(index)"></text> -->
					</view>

					<view v-if="order.order_item.length === 1" class="goods-box-single" v-for="(goodsItem, goodsIndex) in order.order_item"
					 :key="goodsIndex">
						<image class="goods-img" :src="imgsrc + goodsItem.product_pic" mode="aspectFill"></image>
						<view class="right">
							<text class="title clamp">{{goodsItem.product_name}}</text>
							<!-- {{goodsItem.product_attr}} -->
							<text class="attr-box">x {{goodsItem.product_quantity}}</text>
							<text class="price">{{goodsItem.product_price}}</text>
						</view>
					</view>

					<scroll-view v-if="order.order_item.length > 1" class="goods-box" scroll-x>
						<view v-for="(goodsItem, goodsIndex) in order.order_item" :key="goodsIndex" class="goods-item">
							<image class="goods-img" :src="imgsrc + goodsItem.product_pic" mode="aspectFill"></image>
						</view>
					</scroll-view>

					<view class="price-box">
						<text>共</text>
						<text class="num">{{item.order_items.length}}</text>
						<text>件商品订单实付款</text>
						<text class="price">{{item.pay_amount}}</text>
					</view>
					<view class="action-box b-t">
						<!-- <text class="state" :style="{ color: item.stateTipColor }" v-if="item.orderType== 6">秒杀订单</text>
							<text class="state" :style="{ color: item.stateTipColor }" v-else-if="item.orderType== 2">拼团订单</text>
							<text class="state" :style="{ color: item.stateTipColor }" v-else-if="item.orderType== 3">团购订单</text>
							<text class="state" :style="{ color: item.stateTipColor }" v-else-if="item.orderType== 4">砍价订单</text>
							<text class="state" :style="{ color: item.stateTipColor }" v-else-if="item.orderType== 5">积分订单</text> -->
						<!-- <button v-if="item.status == 0" class="action-btn" @click="cancelOrder(item)">取消订单</button>
							<button v-if="item.status == 0" class="action-btn recom" @click="payOrder(item)">立即支付</button> -->
						<button v-if="order.status == 1" class="action-btn" @click.stop="remindShipping">提醒发货</button>
						<template v-if="order.status == 5">
							<button class="action-btn recom" @click.stop="operationOrder(0,'received', index)">确认收货</button>
							<!-- <button class="action-btn" @click="logisticsClick">查看物流</button> -->
						</template>

						<!-- <button v-if="order.status == 6" class="action-btn recom" @click="confimDelivery(order)">立即评价</button> -->

						<!-- <button class='action-btn recom' hover-class="btn-hover" v-if="item.status === 4" @click="toEvaluate(item.id)">立即评价</button> -->
					</view>
				</view>
			</view>

		</mescroll-body>
	</view>
</template>
<script>
	import Api from '@/common/api';
	import MescrollMixin from "@/components/mescroll-uni/mescroll-mixins.js";
	import MescrollMoreItemMixin from "@/components/mescroll-uni/mixins/mescroll-more-item.js";


	export default {
		mixins: [MescrollMixin, MescrollMoreItemMixin], // 注意此处还需使用MescrollMoreItemMixin (必须写在MescrollMixin后面)
		data() {
			return {
				imgsrc: Api.imgsrc,
				downOption: {
					auto: false, // 是否在初始化完毕之后自动执行下拉刷新的回调; 默认true
				},
				// 上拉加载的常用配置
				upOption: {
					auto: false, // 是否在初始化完毕之后自动执行上拉加载的回调; 默认true
					page: {
						num: 0, // 当前页码,默认0,回调之前会加1,即callback(page)会从1开始
						size: 3, // 每页数据的数量,默认3
					},
					noMoreSize: 3, //配置列表的总数量要大于等于 noMoreSize 条菜显示 textNoMore 的提示
					textNoMore: '-- 我是有底线的 --',
					empty: {
						tip: '当前暂无任何订单',
						icon: '/static/empty/empty-order.png'
					}
				},
				dataList: []
			}
		},
		computed: {

		},
		created() {
			let orderItemId = `orderItem${this.i}`;
			uni.$on('update',e =>{
				this.downCallback(); 
			})
			uni.$on(orderItemId, e =>{
				let  operation = e.operation, index = e.index;
				switch (operation) {
					case 'cancel':
						this.i == 0 ? this.dataList[index].status = 2 : this.dataList.splice(index, 1);
					break;
					case 'received':
						this.dataList[index].status = 2; //取消订单 或者 确认订单
						break;
					case 'delete':
						this.dataList.splice(index, 1)
						break;
				}
				if( (orderItemId == 'orderItem0' || orderItemId == 'orderItem1')  && (operation == 'cancel' || operation == 'delete') ){
					uni.$emit('update')
				}
				if(this.dataList.length < 3) this.downCallback(); 
			})
		},
		methods: {
			/**
			 * @param {Object} page
			 * @description 下来刷新回调
			 */
			upCallback(page) {
				let pageNum = page.num; //页码。默认从1开始
				this.loadData(pageNum);
			},
			async loadData(pageNum) {
				let params = {
						'status': this.i,
						'offset': pageNum
					},
					method = 'POST',
					data = await Api.apiCall(method, Api.order.orderList, params, true);
				if (data) {
					console.log(`pageNum: ${pageNum}`)
					if (pageNum == 1) {
						this.preEveryTimeRequestNum = 0;
						this.dataList = []; //如果是第一页需手动置空列表
					}

					let hasNext = this.preEveryTimeRequestNum <= data.length,
						curListLen = data.length;
					this.preEveryTimeRequestNum = data.length;


					if (data.length > 0) {
						this.dataList = this.dataList.concat(data);
						this.$nextTick(() => {
							this.mescroll.endSuccess(curListLen, hasNext);
						});
						console.log(`curListLen: ${curListLen}   hasNext: ${hasNext} `);
						// let orderList = data.filter(item => {
						// 	//添加不同状态下订单的表现形式
						// 	item = Object.assign(item, this.orderStateExp(item.status));
						// 	//演示数据所以自己进行状态筛选
						// 	if (this.i === 0) {
						// 		//0为全部订单
						// 		return item;
						// 	}
						// 	item.state === this.i;
						// 	return item
						// });

						// data.forEach(item => {
						// console.log("start  push" + item.is_paid)
						// if (item.is_paid == 1) { // 已经支付过的订单需要对子订单做处理
						// 	item.orders.filter(item_p => {
						// 		console.log("start  item_p.status" + item.is_paid)
						// 		return Object.assign(item_p, this.orderStateExp(item_p.status));
						// 	});
						// }
						// this.dataList.push(item);
						// })
					} else {
						this.$nextTick(() => {
							this.mescroll.endSuccess(curListLen)
						});
					}
				} else {
					//  请求失败,隐藏加载状态
					console.log(`error`)
					this.mescroll.endErr()
				}

			},
			

			//提醒发货
			remindShipping() {
				uni.showToast({
					title: '提醒商家成功！'
				})
			},

			// 查看物流
			logisticsClick() {
				this.setlogistics(this.logisticsData);
				uni.navigateTo({
					url: "/mall/order/logistics"
				})
			},

			// 订单详情
			orderDetails(id, type, index) {
				uni.navigateTo({
					url: `orderDetails?id=${id}&type=${type}&index=${index}&orderItemId=orderItem${this.i}`
				})
			},

			// //删除订单
			// deleteOrder(item,istotal ) {
			// 	uni.showLoading({
			// 		title: '请稍后'
			// 	})
			// 	setTimeout(() => {
			// 		this.navList[this.tabCurrentIndex].orderList.splice(index, 1);
			// 		uni.hideLoading();
			// 	}, 600)
			// },

			/**操作订单，确认，取消，删除
			 * @param {Object} item  订单
			 * @param {Object} istotal  1 代表主订单， 0 字典订单
			 * @param {Object} operation  cancel: 取消； received：收货  delete
			 */
			
			async operationOrder(istotal, operation, index) {
				
				uni.showLoading({
					title: '请稍后'
				})

				var params = {
					'is_total': istotal,
					'id': this.dataList[index].id,
					'operation': operation
				};
				await Api.apiCall('put', Api.order.operationOrder, params);

				//取消订单后删除待付款中该项
				// let list = this.navList[1].orderList;
				// let index = list.findIndex(val => val.id === item.id);
				// index !== -1 && list.splice(index, 1);

				switch (operation) {
					case 'received':
						this.dataList[index].status = 2; //取消订单 或者 确认订单
						break;
					case 'delete':
						this.dataList.splice(index, 1)
						break;
				}
				if(this.dataList.length == 0) this.downCallback(); 
				uni.hideLoading();


			},

			// statusChange(option) {
			// 	switch (option) {
			// 		case 'cancel':
			// 			return 2;
			// 		case 'received':
			// 			return 2;
			// 	}
			// },
			async pay(id) {
				let url = `/pages/money/pay?id=${id}`;
				uni.navigateTo({
					url: url
				})
			},
		},
		filters: {
			//订单状态文字和颜色
			orderStateExp(state) {
				let stateTip = '',
					stateTipColor = '#E52631';
				switch (state) {
					case 0:
						stateTip = '待付款';
						break;
					case 1:
						stateTip = '待发货';
						break;
					case 2:
						stateTip = '交易关闭';
						// stateTipColor = '#909399';
						break;
					case 5:
						stateTip = '待收货';
						break;
					case 6:
						stateTip = '待评价';
						break;
					case 7:
						stateTip = '完成';
						break;
						//更多自定义
				}
				return stateTip;
			},
		}
	}
</script>

<style lang="scss">
	.order-item {
		display: flex;
		flex-direction: column;
		// padding-left: 30upx;
		background: #fff;
		margin-top: 30upx;
		border-radius: 20upx;

		.i-top {
			display: flex;
			align-items: center;
			height: 88upx;
			padding: 0 30upx;
			font-size: $font-base;
			color: $font-color-dark;
			position: relative;

			.order_number {
				flex: 1;
			}

			.time {
				flex: 1;
			}

			.state {
				color: $base-color;
			}

			.del-btn {
				padding: 10upx 0 10upx 36upx;
				font-size: $font-lg;
				color: $font-color-light;
				position: relative;

				&:after {
					content: '';
					width: 0;
					height: 30upx;
					border-left: 1px solid $border-color-dark;
					position: absolute;
					left: 20upx;
					top: 50%;
					transform: translateY(-50%);
				}
			}
		}

		/* 多条商品 */
		.goods-box {
			height: 240upx;
			padding: 20upx 0 30upx 30upx;
			white-space: nowrap;
			border-bottom: 1upx solid #F7F7F7;

			.goods-item {
				width: 189upx;
				height: 189upx;
				display: inline-block;
				margin-right: 24upx;
			}

			.goods-img {
				display: block;
				width: 100%;
				height: 100%;
			}
		}

		/* 单条商品 */
		.goods-box-single {
			display: flex;
			height: 240upx;
			padding: 20upx 0 30upx 30upx;
			border-bottom: 1upx solid #F7F7F7;

			.goods-img {
				display: block;
				width: 189upx;
				height: 189upx;
			}

			.right {
				flex: 1;
				display: flex;
				flex-direction: column;
				padding: 0 30upx 0 24upx;
				overflow: hidden;

				.title {
					font-size: $font-base + 2upx;
					color: $font-color-dark;
					line-height: 1;
				}

				.attr-box {
					font-size: $font-sm + 2upx;
					color: $font-color-light;
					padding: 10upx 12upx;
				}

				.price {
					font-size: 28upx;
					color: $font-color-dark;

					&:before {
						content: '￥';
						font-size: $font-sm;
						margin: 0 2upx 0 8upx;
					}
				}
			}
		}

		.price-box {
			display: flex;
			height: 88upx;
			justify-content: flex-end;
			align-items: baseline;
			padding: 20upx 30upx;
			font-size: 28upx;
			color: #232323;

			.num {
				margin: 0 8upx;
			}

			.price {
				&:before {
					content: '￥';
					font-size: $font-sm;
					margin: 0 2upx 0 8upx;
				}
			}
		}

		.action-box {
			display: flex;
			justify-content: flex-end;
			align-items: center;
			height: 100upx;
			position: relative;
			padding: 20upx 30upx 30upx 0;
			padding-right: 30upx;
		}

		.action-btn {
			width: 180upx;
			height: 68upx;
			margin: 0;
			margin-left: 24upx;
			padding: 0;
			text-align: center;
			line-height: 68upx;
			font-size: 28upx;
			color: $font-color-dark;
			background: #fff;
			border-radius: 100px;

			&:after {
				border-radius: 100px;
			}

			&.recom {
				// background: #fff9f9;
				color: #E52631;

				&:after {
					border-color: #E52631;
				}
			}
		}
	}
</style>
